package cn.com.cnxfs.relaxchat;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class MyFragment extends Fragment {
    private Context context;
    private String id, nickname_str;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        SharedPreferences preferences = Objects.requireNonNull(getActivity()).getSharedPreferences("db_login",MODE_PRIVATE);
        id = preferences.getString("id","0");
        nickname_str = preferences.getString("nickname","NULL");
        final TextView nickname = getActivity().findViewById(R.id.nickname);
        nickname.setText(nickname_str); //获取昵称并显示

        Button button_clear_chat = getActivity().findViewById(R.id.button_clear_chat);
        Button button_change_pass = getActivity().findViewById(R.id.button_change_pass);
        Button button_change_name = getActivity().findViewById(R.id.button_change_name);
        Button button_logout = getActivity().findViewById(R.id.button_logout);
        Button button_del_account = getActivity().findViewById(R.id.button_del_count);

        button_logout.setOnClickListener(new View.OnClickListener() {  //退出登录按钮
            @Override
            public void onClick(View v) { //退出登录
                SharedPreferences.Editor editor = Objects.requireNonNull(getActivity()).getSharedPreferences("db_login",MODE_PRIVATE).edit();
                editor.clear(); //清空登录状态
                editor.apply();
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish(); //关掉登录页面
            }
        });

        button_del_account.setOnClickListener(new View.OnClickListener() { //删除账号按钮
            @Override
            public void onClick(View v) {  //删除账号
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("确认要删除账号?");
                builder.setMessage("删除账号后将无法还原!确认要继续?!");
                builder.setCancelable(false);
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() { //向后端发送请求
                                try {
                                    FormBody.Builder params = new FormBody.Builder();
                                    params.add("id",id); //添加url参数
                                    OkHttpClient client = new OkHttpClient();
                                    Request request = new Request.Builder()
                                            .url(Api.url[0]+"/login/del").post(params.build())
                                            .build();
                                    Response response = client.newCall(request).execute(); //执行发送指令
                                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(context,"账号已被删除！",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    //下面是强制退出的代码
                                    SharedPreferences.Editor editor = getActivity().getSharedPreferences("db_login",MODE_PRIVATE).edit();
                                    editor.clear(); //清空登录状态
                                    editor.apply();
                                    Intent intent = new Intent(getContext(), LoginActivity.class);
                                    startActivity(intent);
                                    getActivity().finish(); //关掉登录页面
                                }catch (Exception e){
                                    e.printStackTrace();
                                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(context,"账号删除失败！",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });

        button_change_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {  //修改昵称
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("修改昵称");
                final View view = getLayoutInflater().inflate(R.layout.layout_change_name, null);
                final EditText newNickname = view.findViewById(R.id.nickname_input);
                newNickname.setText(nickname_str); //将当前的昵称显示出来
                builder.setView(view);
                builder.setCancelable(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String string = newNickname.getText().toString();
                        if(!string.equals(nickname_str)){  //用户修改了昵称
                            new Thread(new Runnable() {
                                @Override
                                public void run() {  //向后端发送请求
                                    try{
                                        FormBody.Builder params = new FormBody.Builder();
                                        params.add("id",id); //添加url参数
                                        params.add("nickname", string);
                                        OkHttpClient client = new OkHttpClient();
                                        Request request = new Request.Builder()
                                                .url(Api.url[0]+"/login/update_name").post(params.build())
                                                .build();
                                        Response response = client.newCall(request).execute(); //执行发送指令
                                        SharedPreferences.Editor editor = getActivity().getSharedPreferences("db_login",MODE_PRIVATE).edit();
                                        editor.putString("nickname",string);
                                        editor.apply();
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                nickname.setText(string); //在信息页上显示新昵称
                                                Toast.makeText(context,"修改昵称成功！",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(context,"修改昵称失败！",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }
                            }).start();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });

        button_change_pass.setOnClickListener(new View.OnClickListener() { //修改密码按钮
            @Override
            public void onClick(View v) {  //修改密码
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("修改密码");
                final View view = getLayoutInflater().inflate(R.layout.layout_change_passwd, null);
                builder.setView(view);
                builder.setCancelable(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EditText pass1 = view.findViewById(R.id.pass1);
                        EditText pass2 = view.findViewById(R.id.pass2);
                        final String password1 = pass1.getText().toString();
                        String password2 = pass2.getText().toString();
                        if(!password1.equals("") && password1.equals(password2)){ //两遍密码一致
                            new Thread(new Runnable() { //向后端发送请求
                                @Override
                                public void run() {
                                    try{
                                        FormBody.Builder params = new FormBody.Builder();
                                        params.add("id",id); //添加url参数
                                        params.add("password", MD5Utils.encode(password1));
                                        OkHttpClient client = new OkHttpClient();
                                        Request request = new Request.Builder()
                                                .url(Api.url[0]+"/login/update_pass").post(params.build())
                                                .build();
                                        Response response = client.newCall(request).execute(); //执行发送指令
                                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(context,"修改密码成功！",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(context,"修改密码失败！",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }
                            }).start();
                            dialog.cancel();
                        }else{
                            Toast.makeText(context,"两次密码输入不一致或新密码为空！请检查！",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });

        button_clear_chat.setOnClickListener(new View.OnClickListener() { //清空聊天记录按钮
            @Override
            public void onClick(View v) {  //清空聊天记录
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("删除聊天记录");
                builder.setMessage("确认要删除聊天记录?");
                builder.setCancelable(false);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.setPositiveButton("删除记录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 删除本地数据库
                        MyDatabaseHelper dbHelper = new MyDatabaseHelper(context, "database.db", null, 1);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        db.delete("chat","",null);
                        // 删除本地图片缓存
                        File dir = context.getFilesDir();
                        if (dir == null || !dir.exists() || !dir.isDirectory())
                            return;
                        if(dir.exists()){
                            for (File file : dir.listFiles()) {
                                file.delete(); // 删除所有文件
                            }
                            dir.delete(); // 删除目录本身
                        }
                        Toast.makeText(context,"本地聊天记录已清空！",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        });
    }
}
